import {
  strFromU8,
  strToU8,
  unzlibSync,
  zlibSync,
} from 'fflate'

export function compress(str: string) {
  const buf = strToU8(str)
  const compressed = zlibSync(buf, { level: 9 })
  return encodeURIComponent(btoa(strFromU8(compressed, true)))
}

export function decompress(str: string) {
  try {
    const binary = atob(decodeURIComponent(str))

    const buf = strToU8(binary, true)
    const decompressed = unzlibSync(buf)
    const result = strFromU8(decompressed)
    if (result) {
      try {
        return JSON.parse(result) as Record<string, string>
      }
      catch (e) {
        return null
      }
    }
  }
  catch (error) {
    throw new Error('decompress failed')
  }
}
